const crypto = require('crypto');
const axios = require('axios');

async function main() {
  const ret = await refresh({
    type: 'File',
    path: 'test-hema.speiyou.com/index.html',
    accessKeyId: 'a',
    accessKeySecret: 'b'
  });
  console.log(ret.data);
}

// interface RefreshOpt {
//   type: string;
//   path: string;
//   accessKeyId: string;
//   accessKeySecret: string;
// }

async function refresh(opt) {
  const d = new Date();
  const param = {
    Action: 'RefreshObjectCaches',
    ObjectType: opt.type,
    Version: '2018-05-10',
    Timestamp: d.toISOString(),
    SignatureNonce: d.getTime() + '' + Math.random(),
    AccessKeyId: opt.accessKeyId,
    SignatureMethod: 'HMAC-SHA1',
    SignatureVersion: '1.0',
    ObjectPath: opt.path
  }

  let headerString = ''

  const keys = Object.keys(param).sort();
  for (const k of keys) {
    headerString = `${headerString}${k}=${encodeURIComponent(param[k])}&`
  }
  headerString = headerString.slice(0, -1);
  const toSign = `GET&%2F&${encodeURIComponent(headerString)}`
  const sign = crypto.createHmac('sha1', opt.accessKeySecret + '&').update(toSign).digest('base64');
  const url = `https://cdn.aliyuncs.com?Signature=${encodeURIComponent(sign)}&${headerString}`

  return axios.get(url);
}

main();